package com.lonewalker.snail.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.lonewalker.snail.common.base.ApiResult;
import com.lonewalker.snail.constant.ServiceExceptionEnum;
import com.lonewalker.snail.domain.entity.SysUser;
import com.lonewalker.snail.domain.request.CreateDefinitionRequest;
import com.lonewalker.snail.domain.request.DeployRequestParam;
import com.lonewalker.snail.service.ProcessDefinitionService;
import com.lonewalker.snail.util.AssertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.Definitions;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.springframework.stereotype.Service;

import java.util.Collection;


/**
 * @author lonewalker
 */
@Slf4j
@RequiredArgsConstructor
@Service("processDefinitionService")
public class ProcessDefinitionServiceImpl implements ProcessDefinitionService {

    private final RepositoryService repositoryService;


    @Override
    public ApiResult<String> deploy(SysUser user, DeployRequestParam requestParam) {
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource(requestParam.getResourcePath())
                .name(requestParam.getBpmnName())
                //不需要租户的概念可以把这行去掉
                .tenantId(user.getTenantId().toString())
                .deploy();
        AssertUtil.checkService(ObjectUtil.isNull(deploy), ServiceExceptionEnum.SERVE_EXCEPTION.getDesc());
        return ApiResult.success(deploy.getId());
    }

    @Override
    public ApiResult<String> deleteDeployment(String deploymentId) {
        //这里可以做级联删除，默认为false,级联会删除流程实例和job
        //repositoryService.deleteDeployment(deploymentId,true);
        repositoryService.deleteDeployment(deploymentId);
        return ApiResult.successMessage("删除成功");
    }

    @Override
    public ApiResult<String> getBpmnModelInstance(String processDefinitionId) {
        BpmnModelInstance bpmnModelInstance = repositoryService.getBpmnModelInstance(processDefinitionId);
        if (ObjectUtil.isNotNull(bpmnModelInstance)){
            Collection<UserTask> userTasks = bpmnModelInstance.getModelElementsByType(UserTask.class);
            Definitions definitions = bpmnModelInstance.getDefinitions();
            log.info("啥也不是");
        }
        return null;
    }

    @Override
    public ApiResult<String> suspendProcessDefinitionById(String processDefinitionId) {
        repositoryService.suspendProcessDefinitionById(processDefinitionId);
        return ApiResult.successMessage("挂起成功");
    }

    @Override
    public ApiResult<String> convert(CreateDefinitionRequest requestParam) {



        return null;
    }


}
